package com.training.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.base.BaseAdapter;
import com.base.BaseFragment;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.training.activity.CourseListActivity;
import com.training.adapter.HomeAdapter;
import com.training.bean.CourseStage;
import com.training.databinding.FragmentHomeBinding;
import com.training.net.Constant;
import com.training.net.HttpResponse;
import com.training.net.NetCallback;
import com.training.util.ToastyUtil;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class HomeFragment extends BaseFragment<FragmentHomeBinding> {
    private HomeAdapter adapter;

    @Override
    public FragmentHomeBinding binding() {
        return FragmentHomeBinding.inflate(getLayoutInflater());
    }

    @Override
    public void onCreated(Bundle savedInstanceState) {
        adapter = new HomeAdapter(getActivity(), new BaseAdapter.OnItemClickListener<CourseStage>() {
            @Override
            public void onItemClick(int position, CourseStage courseStage) {
                Intent intent = new Intent(getActivity(), CourseListActivity.class);
                intent.putExtra("stageId", courseStage.id);
                startActivity(intent);
            }
        });
        mBinding.dataRv.setLayoutManager(new LinearLayoutManager(context));
        mBinding.dataRv.setAdapter(adapter);
        mBinding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData();
            }
        });
        mBinding.refreshLayout.autoRefresh();
    }

    @Override
    public void loadData() {
        dc.getAllStage(new NetCallback<HttpResponse<ArrayList<CourseStage>>>() {

            @Override
            public void onError(int code, String message) {
                ToastyUtil.showError(context, message, Toast.LENGTH_SHORT, true);
            }

            @Override
            public void onSuccess(HttpResponse<ArrayList<CourseStage>> response) {
                adapter.setData(response.data);
            }

            @Override
            public void onFinally() {
                finishRefresh();
            }
        });
    }

    @Override
    public void refreshUI() {

    }

    private void finishRefresh() {
        mBinding.refreshLayout.finishRefresh(200);
    }
}
